// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
 * @fileoverview This file is used to dynamically generate a form list of device
 * and SSID combinations, for a specified "provider", as well as fetching and
 * generating charts for the selected provider+device+SSID.
 *  
 */

function init() {
  var url = '/provider/details.xml';
  loadDropDownMenuXML(url);
  $('#charts').hide();
}

function loadDropDownMenuXML(_xmlFile) {
  $.ajax({
    url: _xmlFile,
    success: setXML,
    data: ({provider: provider}),
    dataType: 'xml',
    type: 'POST'
  });
}

function setXML(_xml) {
  var _idx = 0;
  var currentOption;
  var currentLocation = $(_xml).find('location');
  $(currentLocation).each(function(i) {
    var location = $(this);
    currentOption = $('<option value="' + $(location).attr('loc') + '">' +
    location.children('label').text() + '</option>');
    currentOption.data('loc', location);
    $(currentOption).appendTo($('#locationList'));
  });
}

function setSSID() {
  var currentLocation = $('#locationList').children(':selected').data('loc'),
      currentSSID = $(currentLocation).find('ssid');
  $('#ssidList').html('');
  if (currentSSID.length >= 1) {
    currentSSID.each(function(i) {
      var ssid = $(this);
      if (i == 0) {
        currentOption = '<option value="null">--Select SSID--</option>' +
        '<option value="' + ssid.text() + '">' + ssid.text() + '</option>';
      } else {
        currentOption = '<option value="' + ssid.text() + '">' + ssid.text() +
        '</option>';
      }
      $(currentOption).appendTo($('#ssidList'));
    });
  } else {
    var ssid = $(this);
    currentOption = '<option value="' + ssid.text() + '">' + ssid.text() +
    '</option>';
    $(currentOption).appendTo($('#ssidList'));
  }
}

function loadSSIDData() {
  var location = $('#locationList').children(':selected').text(),
      ssid = $('#ssidList').children(':selected').text();
  $.ajax({
    url: '/provider/ssiddata',
    success: generateDataTables,
    data: ({provider: provider, location: location, ssid: ssid}),
    dataType: 'json',
    type: 'POST'
  });
}

function generateDataTables(data) {
  var chart_list = [[average_signal, 'average_signal', 'Average Signal'],
                    [best_signal, 'best_signal', 'Best Signal Strength'],
                    [bing_latency, 'bing_latency', 'Bing latency'],
                    [edns_latency, 'edns_latency', 'External DNS latency'],
                    [duration, 'duration', 'Test Duration'],
                    [google_latency, 'google_latency', 'Google latency'],
                    [idns_latency, 'idns_latency', 'Internal DNS latency'],
                    [local_speedtest_down, 'local_speedtest_down',
                    'Local SpeedTest Download (bps)'],
                    [local_speedtest_up, 'local_speedtest_up',
                    'Local SpeedTest Upload (bps)'],
                    [my_signal, 'my_signal', 'My Signal Strength'],
                    [my_speed, 'my_speed', 'My Connection Speed'],
                    [ndt_down, 'ndt_down', 'NDT Download (bps)'],
                    [ndt_up, 'ndt_up', 'NDT Upload (bps)'],
                    [remote_speedtest_down, 'remote_speedtest_down',
                    'Remote SpeedTest Download (bps)'],
                    [remote_speedtest_up, 'remote_speedtest_up',
                    'Remote SpeedTest Upload (bps)'],
                    [temperature, 'temperature', 'Temperature'],
                    [time_since_last_result, 'time_since_last_result',
                    'Time Since Last Result Successfully Posted'],
                    [yahoo_latency, 'yahoo_latency', 'Yahoo latency']
                   ];

  var tables = new Array();
  for (i = 0; i < chart_list.length; i++) {
    tables[i] = new google.visualization.DataTable();
    tables[i].addColumn('datetime', 'Date');
    tables[i].addColumn('number', chart_list[i][2]);
  }

  for (i = 0; i < data.length; i++) {
    var test_result = data[i];
    var this_date = new Date(test_result.date.replace(/-/g, '/') + ' UTC');

    function replaceZeros(chart, value, date, result) {
      if (result[value] == 0) {
        chart.addRow([date, null]);
      } else {
        chart.addRow([date, Number(result[value])]);
      }
    }

    for (j = 0; j < chart_list.length; j++) {
      replaceZeros(tables[j], chart_list[j][1], this_date, test_result);
    }
  }

  var chart_data = new Array();
  for (i = 0; i < chart_list.length; i++) {
    chart_data.push([tables[i], chart_list[i][1]]);
  }

  $('#charts').show();

  var charts = new Array();
  for (i = 0; i < chart_data.length; i++) {
    charts[i] = new google.visualization.AnnotatedTimeLine(
      document.getElementById(chart_data[i][1]));
    charts[i].draw(chart_data[i][0], {});
  }
}

window.onload = init;
